package com.crm.controller.ordersController;

import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporter;
import net.sf.jasperreports.engine.export.ooxml.JRDocxExporterParameter;
import net.sf.jasperreports.engine.util.JRLoader;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.crm.beans.EnquiryBean;
import com.crm.dao.AttachmentHistoryDAO;
import com.crm.dao.ClientdetDAO;
import com.crm.dao.OpportunityDAO;
import com.crm.dao.PartsDAO;
import com.crm.dao.QuotPartsDAO;
import com.crm.dao.QuotationDAO;
import com.crm.dao.SupplyOrderDAO;
import com.crm.entity.AttachmentHistory;
import com.crm.entity.Business;
import com.crm.entity.Clientdet;
import com.crm.entity.Opportunity;
import com.crm.entity.Parts;
import com.crm.entity.QuotParts;
import com.crm.entity.Quotation;
import com.crm.entity.SupplyOrder;
import com.crm.entity.User;
import com.crm.entity.Variables;
import com.crm.util.Constants;
import com.crm.util.NumToWords;

@Controller
@RequestMapping("/supplyOrder")
public class SupplyOrderController {
	protected final Log logger = LogFactory.getLog(getClass());
	@RequestMapping( "/show.do") 
	public ModelAndView show(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
			//OpportunityDAO oprD=new OpportunityDAO();
			List<Opportunity> opr=null;
			try{
				opr=(List<Opportunity>)OpportunityDAO.getSingleInstance().getAllEnqSuppliers(bus.getBusinessId());
					logger.info("opportunity list is "+opr);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			  model = new ModelAndView("/jsp/SupplyOrder.jsp");
				model.addObject("opprtunity",opr);
				model.addObject("submenu", "orders");
				model.addObject("menuName","orders");
				 
		 
				return model;
	}
	@RequestMapping( "/printpi.do") 
	public ModelAndView printpi(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
			AttachmentHistoryDAO atDao=new AttachmentHistoryDAO();
			List<AttachmentHistory> attlist=null;
			List<AttachmentHistory> soclist=null;
			List<AttachmentHistory> bankglist=null;
			List<AttachmentHistory> warlist=null;
			try{attlist=atDao.getAllPi(bus.getBusinessId(),Constants.PROFORMA);
			soclist=atDao.getAllPi(bus.getBusinessId(),Constants.SOCOPY);
			bankglist=atDao.getAllPi(bus.getBusinessId(),Constants.BANKGCOPY);
			warlist=atDao.getAllPi(bus.getBusinessId(),Constants.WARRENTYCOPY);
					logger.info("attachment list is "+attlist);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			  model = new ModelAndView("/jsp/PrintPI.jsp");
				model.addObject("attlist",attlist);
				model.addObject("soclist",soclist);
				model.addObject("bankglist",bankglist);
				model.addObject("warlist",warlist);
				model.addObject("submenu", "orders");
				model.addObject("menuName","orders");
				 
		 
				return model;
	}
	
	
	@RequestMapping(value = "/get_pi", method = RequestMethod.GET)
	public String pinting(HttpSession session, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus = (Business) session.getAttribute("business");

		String idno = request.getParameter("quotid");
		int id=Integer.parseInt(idno);
		AttachmentHistoryDAO atDAO = new AttachmentHistoryDAO();
		AttachmentHistory att = atDAO.getAttachmentHistoryByPI(id);
		logger.info("the business id is  " + bus.getBusinessId());
		byte[] pdfReport = att.getFileBlob();
		logger.info("the length of pdf is" + pdfReport.length);
		logger.info("the length of pdf is" + pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		String fileName = "quotation.doc";
		response.setHeader("Content-Disposition", "inline; filename=" + fileName);
		// response.setContentType("application/pdf");
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		// OutputStream o = response.getOutputStream();
		// o.write(imgData);
		// o.flush();
		// o.close();
		servletOutputStream.flush();
		servletOutputStream.close();
		return null;

	}
	/*@RequestMapping( "/showquot.do") 
	public @ResponseBody String showAllQuot(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		String enqno=req.getParameter("refno");
		logger.info("refrence no is "+enqno);
		QuotationDAO qDAO=new QuotationDAO();
		List<Quotation> qlist=null;
		OpportunityDAO oprDAO=new OpportunityDAO();
	
		int rid=oprDAO.getByRefNo(bus.getBusinessId(),enqno.trim()).getId();
	logger.info("the ref id is "+rid);
	logger.info("the business id is "+bus.getBusinessId());
		StringBuilder sourcelist= new StringBuilder();
		
			qlist=qDAO.getQuotNumByEnq(bus.getBusinessId(),rid);
		logger.info("the source list is"+qlist);
		if (qlist!=null) {
			Iterator it = qlist.iterator();
			while (it.hasNext() == true) {
				Object ob = it.next();
				Quotation quot = (Quotation) ob;

				String qname = quot.getQuotno();
				logger.info("the quotation  no is  is" + qname);
				sourcelist.append("," + qname);
			}
		}
		logger.info("the list of sources is"+sourcelist);
		return sourcelist.toString();
		
	}*/
	@RequestMapping( "/generatePI.do") 
	public @ResponseBody String generatePI(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		String enqno=req.getParameter("refno");
		logger.info("refrence no is "+enqno);
	
		//OpportunityDAO oprDAO=new OpportunityDAO();
		
		
		Opportunity p=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),enqno.trim());
		
		
		String cmpName=bus.getShortname();
		String custName=p.getClientId().getOrganisation();
		ClientdetDAO clDAO=new ClientdetDAO();
		
		
		Clientdet cN=clDAO.getCliOrg(bus.getBusinessId(),custName);
		String cNam=cN.getShrtname();
		String enqType=p.getEnquirytype();
		SupplyOrderDAO supDAO=new SupplyOrderDAO();
		
		Long c=supDAO.getCount(bus.getBusinessId());

		DateFormat formatter1 =Constants.DD_MM_YYYY;
		Date date1 = Constants.cal.getTime();
		String dt= formatter1.format(date1);
		
		String invNo=cmpName+"/"+cNam+"/"+enqType+"/"+c+"/"+dt;
	
		logger.info("the generated invoice no is"+invNo);
		return invNo;
		
	}
	
	@RequestMapping( "/getqparts.do") 
	public ModelAndView showParts(HttpServletRequest req,HttpSession session, ModelAndView model) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		if(bus==null)return new ModelAndView("/jsp/index.jsp");
		int busid=bus.getBusinessId();
		String enqno=req.getParameter("refno");
		
		//OpportunityDAO oppDAO=new OpportunityDAO();
		QuotationDAO qDAO=new QuotationDAO();
		Opportunity opp=OpportunityDAO.getSingleInstance().getByRefNo(busid,enqno.trim());
		int rid=opp.getId();
		Quotation quot=qDAO.getPendingQuot(rid,bus.getBusinessId());
		
		String quotno=quot.getQuotno();
		logger.info("refrence no is "+enqno);
		logger.info("quotation  no is "+quotno);
		System.out.println("Quotation Number Is: "+quotno);
		List<QuotParts> qplist=new ArrayList<QuotParts>();
	QuotPartsDAO qpDAO=new QuotPartsDAO();
	
	qplist=qpDAO.getPartsByQuot(quotno,rid,busid);
	System.out.println("Quot Parts List Is: "+qplist);
	
	DateFormat formatter =Constants.DD_MM_YYYY;
	Date date1 =  Constants.cal.getTime();
	
	String address=opp.getClientId().getAddr();
	String curdate= formatter.format(date1);
	logger.info("the ref id is "+rid);
	logger.info("the business id is "+bus.getBusinessId());
	
	  model = new ModelAndView("/jsp/SupplierOrderRes.jsp");
		model.addObject("quotpartslist",qplist);
		model.addObject("curdate",curdate);
		model.addObject("address",address);
		model.addObject("clientdet",opp.getOrganisation());
		model.addObject("division",opp.getDivision());
		model.addObject("user",opp.getUser());
		model.addObject("submenu", "orders");
		model.addObject("menuName","orders");
	
	return model;
}
	
	@RequestMapping( "/savesupplier.do") 
	public ModelAndView saveParts(HttpServletRequest request,HttpServletResponse response,HttpSession session) throws Exception{
		Business bus=(Business)session.getAttribute("business");
		User user=(User)session.getAttribute("user");
		
		
		String refno=request.getParameter("reflist");
		logger.info("the reference number is"+refno);
		//OpportunityDAO oprDAO=new OpportunityDAO();
		Opportunity opp=OpportunityDAO.getSingleInstance().getByRefNo(bus.getBusinessId(),refno.trim());
		int rid=opp.getId();
		
		String sonum=request.getParameter("sonumber");
		String sodate=request.getParameter("sodate");
		String pinum=request.getParameter("pinum");
		String pidate=request.getParameter("pidate");
		String soedate=request.getParameter("soedate");
		String billto=request.getParameter("billto");
		String shipto=request.getParameter("shipto");
		String bgcheck=request.getParameter("bgcheck");
		String warcheck=request.getParameter("warcheck");
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = null;
		try{
			file=multipartRequest.getFile("sordercopy");
			System.out.println("In Try Ending");
		}catch(NullPointerException npe){
			npe.printStackTrace();
		}
		byte[] socopy=file.getBytes();
		String sofiletype=file.getContentType();
		System.out.println("File Type is Is: "+sofiletype+""+socopy);
		MultipartFile bankfile = null;
		String bgdate=null;
		String bgedate=null;
		Date bgdate1=null;
		Date bgedate1=null;
		Date wardate1=null;
		Date waredate1=null;
		
		DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
		Date  sdate = formatter.parse(sodate);
		Date  pdate = formatter.parse(pidate);
		Date  sedate = formatter.parse(soedate);
		
		if(bgcheck!=null)
		{
			bgdate=request.getParameter("bgdate");
			System.out.println("the bggurantee date"+bgdate);
			bgedate=request.getParameter("bgedate");
			System.out.println("the bggurantee end date"+bgedate);
			bgdate1=formatter.parse(bgdate);
			bgedate1=formatter.parse(bgedate);
			
			
			try{
				bankfile=multipartRequest.getFile("bankcopy");
				System.out.println("In Try Ending");
			}catch(NullPointerException npe){
				npe.printStackTrace();
			}
		}
		
		MultipartFile warfile = null;
		String wardate=null;
		String waredate=null;
		byte[] warbyte=null;
		String warfiletype=null;
		if(warcheck!=null)
		{
			wardate=request.getParameter("wargdate");
			System.out.println("the waraenty  date"+wardate);
			waredate=request.getParameter("waredate");
			System.out.println("the warrentyend end date"+bgedate);
			wardate1=formatter.parse(wardate);
			waredate1=formatter.parse(waredate);
		try{
			warfile=multipartRequest.getFile("bankcopy");
			warbyte=warfile.getBytes();

			warfiletype=warfile.getContentType();
			System.out.println("In Try Ending");
		}catch(NullPointerException npe){
			npe.printStackTrace();
		}
		}
		byte[] bankcopy=null;
		String bankfiletype=null;
		if(bankfile!=null){
			bankcopy=bankfile.getBytes();
			bankfiletype=bankfile.getContentType();
		}
		
		System.out.println("bank File Bytes Is: "+bankcopy);
		
		
		
		
		
		System.out.println("warrenty file Bytes Is: "+warbyte);
		
		
		logger.info("due date "+sodate);
		
		
		
		
		try{
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		
		SupplyOrderDAO soDAO=new SupplyOrderDAO();
		Quotation quotObj=new Quotation();
		QuotationDAO quotDAO=new QuotationDAO();
		System.out.println("ref id is"+rid+"business obj is"+bus.getBusinessId());
		quotObj=quotDAO.getPendingQuot(rid,bus.getBusinessId());
		System.out.println("quotation obj is"+quotObj);
		int quotid=quotObj.getId();
		List<com.crm.beans.SupplyParts> lstsp=new ArrayList<com.crm.beans.SupplyParts>();
		SupplyOrder so=new SupplyOrder();
		
		PartsDAO partDAO =new PartsDAO();
		Parts p =new Parts();
		
		List<SupplyOrder> lso=new ArrayList<SupplyOrder>();
		
		float subtotal=0;
				String rcount=request.getParameter("rowcount");
				int rowcount=Integer.parseInt(rcount);
				logger.info("row count "+rowcount);
				Variables v=new Variables();
				for(int i=0;i<rowcount;i++){
					String partNum=request.getParameter("partno"+i);
					String partId=request.getParameter("partid"+i);
					System.out.println("part number "+partId);
					
					int partno=Integer.parseInt(partId);
					p=partDAO.getById(rid,partno,bus.getBusinessId());
				
					String sno=request.getParameter("sno"+i);
					String required=request.getParameter("qty"+i);
					int rQty=Integer.parseInt(required);
					
					String uprice=request.getParameter("uprice"+i);
					float unitprice=Float.parseFloat(uprice);
				
					String discount=request.getParameter("discount"+i);
					int dcount=Integer.parseInt(discount);
					String podis=request.getParameter("padiscount"+i);
					float pdis=Float.parseFloat(podis);
					
					
				
					so=new SupplyOrder(quotid,partno,rQty,unitprice,dcount,pdis,pinum,new java.sql.Date(sdate.getTime()),sonum,new java.sql.Date(pdate.getTime()),bus);
					if(bgcheck!=null){
						so.setBgdate(new java.sql.Date(bgdate1.getTime()));
						so.setBgedate( new java.sql.Date(bgedate1.getTime()));	
					}
					if(warcheck!=null){
						so.setWargdate(new java.sql.Date(wardate1.getTime()));
						so.setWaredate(new java.sql.Date(waredate1.getTime()));	
					}
					so.setSoStartDate(sdate);
					so.setSoEndDate(sedate);
					lso.add(so);
				
					
					float qty=Float.parseFloat(required);
					float actcost=unitprice*qty;
					
				
					
					subtotal=subtotal+actcost;
					logger.info("Total Cost Is :"+subtotal);
					String cost=""+actcost;
					String partdesc=p.getDescription();
					com.crm.beans.SupplyParts sp=new com.crm.beans.SupplyParts(partNum,partdesc,p.getMake(), required.toString(),uprice.toString(),cost.toString() , sno.toString());	
				     lstsp.add(sp);
				}
				
				
				Opportunity refid=quotObj.getEnqid();
				
				float vat=((subtotal*v.getVatPercent()));
				System.out.println("Vat Value Is: "+vat);
				DecimalFormat df = new DecimalFormat("#.##");
				System.out.println("After Converting to decimals "+df.format(vat));

			
				Opportunity op=OpportunityDAO.getSingleInstance().findById(refid.getId(),bus.getBusinessId());
				
				
				
				
				String terms=request.getParameter("termsAndConditions");
			
				String tinNo=bus.getTinno();
				String cstNo=bus.getCstno();
				String panNo=bus.getPanno();
				long lmicr=bus.getMicr();
				String micr=Long.toString(lmicr);
				String ifsc=bus.getIfsc();
				long laccno=bus.getAccno();
				String accno=Long.toString(laccno);
				
			
				Map<String,String> parms = new HashMap<String,String>();
				 
				
				String custName=op.getClientId().getOrganisation();
				ClientdetDAO clDAO=new ClientdetDAO();
				
				Clientdet client=clDAO.getCliOrg(bus.getBusinessId(),custName);
				//it is shifted to Invoice after new changes has given
				int grandTot=(int) (subtotal+vat);
				NumToWords numtoword=new NumToWords();
				String priceword=numtoword.convert(grandTot);
				
				 parms.put("sodate",sodate);
				 parms.put("customer",client.getOrganisation());
				 parms.put("custaddr", client.getAddr());
				 parms.put("invoiceno",pinum);
			
				formatter = new SimpleDateFormat("yyyy-MM-dd");
				Date date  = formatter.parse(sodate);
				 parms.put("date",date.toString());
				 parms.put("total",grandTot+"");
				 parms.put("subtotal",subtotal+"");
				 parms.put("from",bus.getBusinessName() );
				 parms.put("terms",terms);
				 parms.put("tinno",tinNo);
				 parms.put("cstno", cstNo);
				 parms.put("panno", panNo);
				 parms.put("sonumber", sonum);
				 parms.put("micrno", micr);
				 parms.put("ifsccode", ifsc);
				 parms.put("sbiacno", accno);
				 parms.put("vat", vat+"");
				 parms.put("billto",billto);
				 parms.put("shipto",shipto);
				 parms.put("priceword", "Total In "+opp.getCurencytype()+" (In Words)"+priceword+" Only  ");
				 parms.put("manager", user.getUserName()+"\n Operations Manager.");
				 
				 session= request.getSession();


					JasperReport report = (JasperReport) JRLoader.loadObject(session.getServletContext().getResourceAsStream("/WEB-INF/classes/reports/ProInvoice.jasper"));

					//Object[] qparts={"hai","hello"};
					//String name="hello world";
					//Object[] qparts={name};
					JasperPrint prt = JasperFillManager.fillReport(report,parms,new JRBeanArrayDataSource(lstsp.toArray()));
					byte[] pdfReport = JasperExportManager.exportReportToPdf(prt);
					
					
					JRDocxExporter docExporter=new JRDocxExporter();
					ByteArrayOutputStream docStream=new ByteArrayOutputStream();
					docExporter.setParameter(JRDocxExporterParameter.JASPER_PRINT,prt);
					docExporter.setParameter(JRDocxExporterParameter.OUTPUT_STREAM,docStream);
					docExporter.setParameter(JRDocxExporterParameter.FLEXIBLE_ROW_HEIGHT, Boolean.TRUE);
					docExporter.exportReport();
					pdfReport = docStream.toByteArray();
					
					logger.info("the bus object is"+bus.getBusinessId());
					
					AttachmentHistory attachment=new AttachmentHistory("application/msword",bus,Constants.PROFORMA,pdfReport,op.getRefNum(),pinum,new java.util.Date());
					AttachmentHistory socatt=new AttachmentHistory(sofiletype,bus,Constants.SOCOPY,socopy,op.getRefNum(),pinum,new java.util.Date());
					AttachmentHistory bankatt=new AttachmentHistory(bankfiletype,bus,Constants.BANKGCOPY,bankcopy,op.getRefNum(),pinum,new java.util.Date());
					AttachmentHistory waratt=new AttachmentHistory(warfiletype,bus,Constants.WARRENTYCOPY,warbyte,op.getRefNum(),pinum,new java.util.Date());
					AttachmentHistoryDAO atDAO=new AttachmentHistoryDAO();
					try{
						soDAO.insertList(lso);
						
						atDAO.insert(attachment);
						atDAO.insert(socatt);
						atDAO.insert(bankatt);
						atDAO.insert(waratt);
						String status=Constants.ST_GENERATED_SO;
						OpportunityDAO.getSingleInstance().updateStatus(bus.getBusinessId(),status , rid);
						System.out.println("Successfully Inserted Supply Order.");
					}catch(Exception e){
						e.printStackTrace();
						System.out.println("Failed To Insert Supply Order.");
					}
					
				
					logger.info("the length of pdf is"+pdfReport.length);
					logger.info("the length of pdf is"+pdfReport.toString());
				
					
					ModelAndView model=new ModelAndView("/jsp/Proforma.jsp");
					model.addObject("genPINo",pinum);
					model.addObject("resmsg","Sucesssfully Created ProformaInvoice With Number"+pinum);
					model.addObject("submenu", "orders");
					model.addObject("menuName","orders");
					 
					return model;
	}
	@RequestMapping("/get_history.do")
	public String htmlReport(HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus=(Business)session.getAttribute("business");

		String quotno=request.getParameter("quotid");
		AttachmentHistoryDAO atDAO=new AttachmentHistoryDAO();
		
		AttachmentHistory att=atDAO.getAttachmentHistoryByRefno(bus.getBusinessId(),Constants.PROFORMA,quotno.trim());
		logger.info("the quotation no is "+quotno.trim());
		logger.info("the business id is  "+bus.getBusinessId());
		byte[] pdfReport =att.getFileBlob();
		logger.info("the length of pdf is"+pdfReport.length);
		logger.info("the length of pdf is"+pdfReport.toString());
		ServletOutputStream servletOutputStream = response.getOutputStream();
		response.setContentType("application/msword");
		response.setContentLength(pdfReport.length);
		servletOutputStream.write(pdfReport);
		servletOutputStream.flush();
		servletOutputStream.close(); 
		return null;
	   
	}
	@RequestMapping("/getBankGuarntee.do")
	public ModelAndView getbankGuarntee(HttpSession session,HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Business bus=(Business)session.getAttribute("business");
		SupplyOrderDAO soDAO=new SupplyOrderDAO();
	List<EnquiryBean> enqlist=soDAO.getBankGivenInfo(bus.getBusinessId());
		ModelAndView model=new ModelAndView("/jsp/bankGuarntee.jsp");
		model.addObject("oplist",enqlist);
		model.addObject("submenu", "reports");
		model.addObject("menuName","reports");
		 
		return model;
	   
	}
	@RequestMapping("/bankalerts.do")
	public ModelAndView alerts(HttpSession session,ModelAndView model) throws HibernateException, Exception{
		Business bus=(Business)session.getAttribute("business");
		
		SupplyOrderDAO soDAO=new SupplyOrderDAO();
		List<EnquiryBean> enqlist=soDAO.getBankAlerts(bus.getBusinessId());
		System.out.println("Bank Alerts Size Is:"+enqlist.size());
			model=new ModelAndView("/jsp/BankAlerts.jsp");
			model.addObject("oplist",enqlist);
			model.addObject("submenu", "orders");
			model.addObject("menuName","orders");
		return model;
		
	}

}
